<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="450px" :title="`${drawerProps.title}产品`">
    <el-form
      ref="ruleFormRef"
      label-width="100px"
      label-suffix=" :"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="drawerProps.row"
      :hide-required-asterisk="drawerProps.isView"
    >
      <el-form-item label="产品名称" prop="productName">
        <el-input v-model="drawerProps.row!.productName" placeholder="请填写产品名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="产品描述" prop="description">
        <el-input
          type="textarea"
          v-model="drawerProps.row!.description"
          placeholder="请填写产品描述"
          clearable
          :rows="5"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="drawerVisible = false">取消</el-button>
      <el-button type="primary" v-show="!drawerProps.isView" @click="handleSubmit">确定</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="ProductDrawer">
import { ref, reactive } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { Product } from "@/api/interface";
import axios from "axios";
const baseUrl = import.meta.env.VITE_BASE_URL;

const rules = reactive({
  productId: [{ required: true, message: "请输入产品编号", trigger: "blur" }], // 产品编号
  productName: [{ required: true, message: "请输入产品名称", trigger: "blur" }], // 产品名称
  description: [{ required: true, message: "请输入产品描述", trigger: "blur" }] // 产品描述
});

interface DrawerProps {
  owner: string;
  title: string;
  isView: boolean;
  row: Partial<Product.ResProduct>;
}
const emit = defineEmits(["submit"]);

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  owner: "",
  isView: false,
  title: "",
  row: {}
});

// 接收父组件传过来的参数
const acceptParams = (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;
};

function formatDate(date: Date): string {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0"); // 月份从0开始，因此需要加1
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  const seconds = String(date.getSeconds()).padStart(2, "0");
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  const userInfo = JSON.parse(localStorage.getItem("userInfo") || "{}");
  const userId = Number(userInfo.id) || 0; // 如果没有 id，则使用默认值 0
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    console.log(drawerProps.value.row);
    try {
      //静态数组新增数据
      if (drawerProps.value.title === "新增") {
        drawerProps.value.row.createTime = formatDate(new Date());
        const response = await axios.post(baseUrl + "/api/carbon/createProduct", {
          productName: drawerProps.value.row.productName,
          userId: userId,
          description: drawerProps.value.row.description
        });
        if (response.data && response.data.code === 200) {
          ElMessage.success("新增产品成功！");
          emit("submit"); // 通知父组件刷新
        } else {
          ElMessage.error(response.data.msg || "新增产品失败");
        }
      }
      //静态数组编辑数据
      else if (drawerProps.value.title === "编辑") {
        const response = await axios.post(baseUrl + "/api/carbon/editProduct", {
          id: drawerProps.value.row.id, // 编辑时需要传id
          productName: drawerProps.value.row.productName,
          owner: userId,
          description: drawerProps.value.row.description
        });
        if (response.data && response.data.code === 200) {
          ElMessage.success("更新产品信息成功！");
          emit("submit"); // 通知父组件刷新
        } else {
          ElMessage.error(response.data.msg || "更新产品信息失败");
        }
      }
      // 添加以下代码：通知父组件数据已更新
      emit("submit");
      drawerVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};

defineExpose({
  acceptParams
});
</script>
